package com.psa.element;

import android.database.Cursor;
import android.util.Log;
import com.psa.system.MainActivity;
import com.psa.system.R;
import com.psa.tool.DBTool;
import com.psa.tool.ReflectionTool;
import com.psa.tool.SystemStatus;
import com.wxw.BaseLibrary.component.*;
import com.wxw.BaseLibrary.element.IListBoxItem;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by david on 2014-07-14.
 */
public class CustomerFieldEditor {
    private ListBox listBox;
    private String changedValue;
    private Field field = null;
    private Customer customer = null;
    private Column column = null;
    private IListBoxItem item = null;
    private boolean isNew = true;
//    private boolean isChanged = false;
    private int index = 0;
    private List<Object> objects = null;
    private OnValueChangedListener onValueChangedListener;

    public CustomerFieldEditor(Customer customer, Field field, ListBox listBox, boolean isNew){
        this.customer = customer;
        this.field = field;
        column = field.getAnnotation(Column.class);
        this.listBox = listBox;
        this.isNew = isNew;
        initItem();
    }

    public int index(){
        return column!=null?column.index():-1;
    }

    public IListBoxItem getItem() {
        return item;
    }

    public boolean isChanged() {
        return item.isChanged();
    }

    public boolean isNew() {
        return isNew;
    }

    public Column getColumn() {
        return column;
    }

    public Field getField() {
        return field;
    }

    public Object getChangedValue() {
        if (column.type() == FieldType.NUMBER) {
            try {
                return Integer.valueOf(changedValue);
            } catch (Exception e) {
                Log.e(SystemStatus.TAG, e.getMessage());
                return -1;
            }
        }
        return changedValue;
    }

    public void setOnValueChangedListener(OnValueChangedListener onValueChangedListener) {
        this.onValueChangedListener = onValueChangedListener;
    }

    private void initItem(){
        boolean b = listBox.isEditable();
        listBox.setEditable(false);
        changedValue = ReflectionTool.getFieldValue(customer, field);
        switch (column.inputType()) {
            case 0:
                item = new ListBoxEditItem(listBox);
                ((ListBoxEditItem)item).setCaption((column.caption()!=""?column.caption():column.name())+":");
//                changedValue = CreateSqlTools.getFieldValue(customer, field);
                ((ListBoxEditItem)item).setValue(changedValue.toString());
                if (!isNew) ((ListBoxEditItem)item).setEnabled(!column.isPrimaryKey());
                break;
            case 1:
                item = new ListBoxSpinnerItem(listBox, getData());
                ((ListBoxSpinnerItem)item).setSelectedIndex(index);
                ((ListBoxSpinnerItem)item).setCaption((column.caption()!=""?column.caption():column.name())+":");
//                changedValue = getSelectionValue();
//                ((ListBoxSpinnerItem)item).setValue(changedValue.toString());
                break;
            default:
                item = new ListBoxCheckItem(listBox);
                ((ListBoxCheckItem)item).setCaption((column.caption()!=""?column.caption():column.name())+":");
                if (changedValue!=null)
                    ((ListBoxCheckItem)item).setChecked(changedValue.toString().trim().equals("1"));
                break;
        }
        if (item!=null){
            item.setKey(column.name());
            item.setOnListBoxItemChangedListener(new ListBox.OnListBoxItemChangedListener() {
                @Override
                public void onItemChanged(IListBoxItem item, Object o) {
                    Class cls = String.class;
                    if (column.type() == FieldType.NUMBER)
                        cls = int.class;
                    if (item instanceof ListBoxSpinnerItem) {
                        if (((ListBoxSpinnerItem) item).getSelectedIndex() != index) {
                            item.setChanged(true);
                            index = ((ListBoxSpinnerItem) item).getSelectedIndex();
                            Object obj = objects.get(index);
                            if (obj instanceof Channel)
                                changedValue = ((Channel) obj).ID;
                            if (obj instanceof Department)
                                changedValue = ((Department) obj).ID;
                            if (obj instanceof District)
                                changedValue = ((District) obj).ID;
                            if (obj instanceof TradeMode)
                                changedValue = ((TradeMode) obj).ID;
                            try {
                                ReflectionTool.setFieldValue(customer, field, changedValue, cls);
                            } catch (Exception e) {

                            }
                            if (onValueChangedListener != null)
                                onValueChangedListener.onChange(CustomerFieldEditor.this, index);
                        }
                    } else if (item instanceof ListBoxCheckItem) {
                        if (o instanceof Boolean){
                            boolean b = (Boolean)o;
                            String val = b?"1":"0";
                            if (changedValue == null || !changedValue.equals(val)) {
                                changedValue = val;
                                try {
                                    ReflectionTool.setFieldValue(customer, field, changedValue, cls);
                                }catch (Exception e){

                                }
                                item.setChanged(true);
                                if (onValueChangedListener != null)
                                    onValueChangedListener.onChange(CustomerFieldEditor.this, o);
                            }
                            changedValue = b?"1":"0";
                        }
                    } else {
                        if (changedValue == null || !changedValue.equals(o.toString())) {
                            changedValue = o.toString();
                            try {
                                if (column.type() == FieldType.NUMBER)
                                    ReflectionTool.setFieldValue(customer, field, Integer.parseInt(changedValue), cls);
                                else
                                    ReflectionTool.setFieldValue(customer, field, changedValue, cls);
                            }catch (Exception e){
                                ((MainActivity)SystemStatus.MainActivity).showMessage(e.getMessage());
                                e.printStackTrace();
                            }
                            item.setChanged(true);
                            ((ListBoxEditItem) item).setBackgroundColor(new int[]{SystemStatus.MainActivity.getResources().getColor(R.color.cc_yellow_end)});
                            if (onValueChangedListener != null)
                                onValueChangedListener.onChange(CustomerFieldEditor.this, o);
                        }
                    }
                }
            });
        }
        listBox.setEditable(b);
    }

    private List<Object> getData(){
        objects = new ArrayList<Object>();
        Cursor cursor = null;
        int i = 0;
        if (column.name().equals("BusinessType")) {
            cursor = DBTool.getInstance().query("Select * From Channel");
            Channel channel = new Channel();
            while ((channel = (Channel) channel.full(cursor)) != null) {
                if (channel.ID.equals(customer.getBusinessType()))
                    index = i;
                i++;
                objects.add(channel);
            }
        } else if (column.name().equals("ManagedDepartment")) {
            cursor = DBTool.getInstance().query("Select * From Department");
            Department department = new Department();
            while ((department = (Department) department.full(cursor)) != null) {
                if (department.ID.equals(customer.getManagedDepartment()))
                    index = i;
                i++;
                objects.add(department);
            }
        } else if (column.name().equals("DistrictID")) {
            cursor = DBTool.getInstance().query("Select * From District");
            District district = new District();
            while ((district = (District) district.full(cursor)) != null) {
                if (district.ID.equals(customer.getDistrictID()))
                    index = i;
                i++;
                objects.add(district);
            }
        } else {
            cursor = DBTool.getInstance().query("Select * From TradeMode");
            TradeMode tradeMode = new TradeMode();
            while ((tradeMode = (TradeMode) tradeMode.full(cursor)) != null) {
                if (tradeMode.ID.equals(customer.getTradeMode()))
                    index = i;
                i++;
                objects.add(tradeMode);
            }
        }
        if (cursor!=null)cursor.close();
        return objects;
    }

    private String getSelectionValue(){
        if (column.name().equals("BusinessType")) {
            return customer.getBusinessType();
        } else if (column.name().equals("ManagedDepartment")) {
            return customer.getManagedDepartment();
        } else if (column.name().equals("DistrictID")) {
            return customer.getDistrictID();
        } else {
            return customer.getTradeMode();
        }
    }

    public interface OnValueChangedListener{
        void onChange(CustomerFieldEditor customerFieldEditor, Object object);
    }
}
